/**
 * 
 */
package com.technodo.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import android.util.Log;
/**
 * @author Gaurav
 *
 * Useful functions used to parse json files
 * 
 */
public class JsonUtils {
	private static String TAG = "JsonUtils";
	// Global Preferences
	private static GlobalPreferences globalPreferences = GlobalPreferences
			.getGlobalPreferences();

	/**
	 * Reads a file and gets the Json string from the file
	 * 
	 * @param jsonfilename file to read the json from
	 * @return
	 */
	public static String GetJsonFromFile(String jsonfilename) {

		Log.i(TAG, "Parsing File : " + jsonfilename);

		InputStream is = null;
		String strJson = null;

		try {
			is = new BufferedInputStream(new FileInputStream(
					globalPreferences.getDataDir() + jsonfilename));
			strJson = readRawTextFile(is);
		} catch (NullPointerException n) {
			Log.e(TAG,
					"Null Pointer Exception opening json file "
							+ n.getMessage());
		} catch (FileNotFoundException f) {
			Log.e(TAG,
					"FileNotFoundException Opening Rules file "
							+ f.getMessage());
			f.printStackTrace();
		} finally {
			try {
				if(is != null) {
					is.close();
				}
			} catch (IOException e) {
				Log.e(TAG,
						"IOException Closing Rules file " + e.getMessage());
				e.printStackTrace();
			}
		}
		return strJson;
	}

	/**
	 * Reads bytes from json file
	 * 
	 * @param inputStream Input stream to read the string from
	 * @return
	 */
	public static String readRawTextFile(InputStream inputStream) {
		InputStreamReader inputreader = new InputStreamReader(inputStream);
		BufferedReader buffreader = new BufferedReader(inputreader);
		String line;
		StringBuilder text = new StringBuilder();

		try {
			while ((line = buffreader.readLine()) != null) {
				text.append(line);
				text.append('\n');
			}
		} catch (IOException e) {
			return null;
		}
		return text.toString();
	}


}
